package com.localjoycommunity.cpdj.project.system.controller;

import com.localjoycommunity.cpdj.common.R;
import com.localjoycommunity.cpdj.common.utils.QiNiu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author aqie
 * @date 2020-11-12 9:29
 * @function
 */
@RestController
@RequestMapping("system/upload")
@Slf4j
public class Upload2Controller {
    //获取文件存储路径
    @Value("${upload.uploadFolder}")
    private String upfilePath;

    @Value("${upload.staticPath}")
    private String staticPath;

    @Value("${upload.serverUrl}")
    private String serverUrl;

    @Value("${upload.qiniuDomain}")
    private String qiniuDomain;




    @RequestMapping(value = "/file", method = RequestMethod.POST)
    public R<Map<String, Object>> fileUploadOne(@RequestParam("file") MultipartFile file,
                                                @RequestParam(value = "fileType",required = false) String fileType) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        // 获得原始文件名+格式
        String fileName = file.getOriginalFilename();
        //截取文件名
        String fname = fileName.substring(0, fileName.lastIndexOf("."));
        //截取文件格式
        String format = fileName.substring(fileName.lastIndexOf(".") + 1);
        //获取当前时间(精确到毫秒)
        long MS = System.currentTimeMillis();
        String timeMS = String.valueOf(MS);
        //原文件名+当前时间戳作为新文件名
        String videoName = fname + "_" + timeMS + "." + format;
        String filelocalPath = "";
        char pathChar = upfilePath.charAt(upfilePath.length() - 1);
        Date date = new Date();
        String dateOne = new SimpleDateFormat("yyyy/MM/dd/").format(date);
        if (pathChar == '/') {
            filelocalPath = upfilePath + dateOne;
        } else {
            filelocalPath = upfilePath + "/" + dateOne;
        }
        File f = new File(filelocalPath);
        if (!f.exists()) {
            f.mkdirs();
        }
        if (!file.isEmpty()) {
            try {
                FileOutputStream fos = new FileOutputStream(filelocalPath + videoName);
                InputStream in = file.getInputStream();
                //InputStream in = request.getInputStream();
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = in.read(bytes)) != -1) {
                    fos.write(bytes, 0, len);
                }
                fos.close();
                in.close();
                // resMap.put("path",serverUrl + staticPath + dateOne + videoName);
                resMap.put("filename",staticPath + dateOne + videoName);
                resMap.put("localPath",filelocalPath+videoName);
                String uploadQiniu = QiNiu.upload(filelocalPath + videoName);
                resMap.put("path", qiniuDomain + uploadQiniu);
                deleteFile(filelocalPath+videoName);
                return R.success(resMap);
            } catch (Exception e) {

                log.error("ERROR",  e);
            }
        }
        return null;

    }

    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
}
